package com.changgou.jwt;
//令牌的生成和解析

import io.jsonwebtoken.*;
import org.junit.Test;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtTest {
    //    生成jwt
    @Test
    public void testCreateToken() {
        JwtBuilder builder = Jwts.builder();
        builder.setIssuer("黑马训练营");//颁发者.
        builder.setIssuedAt(new Date());//颁发时间
        builder.setExpiration(new Date(System.currentTimeMillis() + 200000));//过期时间
        builder.setSubject(" JWT令牌测试"); //主题信息 .
        builder.signWith(SignatureAlgorithm.HS256, "itcast"); //1: 签名算法 2:秘钥(盐)
        //自定义载荷信息
        Map<String, Object> userInfo = new HashMap<String, Object>();
        userInfo.put(".company", "黑马训练营");
        userInfo.put(" address", "中南海");
        userInfo.put("address", "中南海");
        userInfo.put("money", 3500);
        builder.addClaims(userInfo);
        System.out.println(builder.compact());
    }

    @Test
    public void parseToken() {
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiLpu5Hpqazorq3nu4PokKUiLCJpYXQiOjE1OTE1ODQ1ODgsImV4cCI6MTU5MTU4NDc4OCwic3ViIjoiIEpXVOS7pOeJjOa1i-ivlSIsIi5jb21wYW55Ijoi6buR6ams6K6t57uD6JClIiwiYWRkcmVzcyI6IuS4reWNl-a1tyIsIm1vbmV5IjozNTAwLCIgYWRkcmVzcyI6IuS4reWNl-a1tyJ9.v8RPoOJl7RpYegM8KcbpzZXz2vS7bucEk1AycRToYN4";
        Claims claims = Jwts.parser().setSigningKey("itcast")//秘钥(盐巴)
                .parseClaimsJws(token)
                .getBody();//要解析的令牌
        System.out.println(claims);
    }
}
